import { wxReLaunch, wxNavigateTo, wxNavigateBack, wxPayApi } from './wxApi'
import { getUserProfile } from './index'
import { getParam, setTotalUnreadCount } from './util'
import store from '../store/index'
import Vue from 'vue'
let $bus = new Vue()
export function getSDKAppId() {
  // 1400471748 本地
  // 1400461245 fat
  // 1400556792 uat
  // 1400462535 生产
  return 1400471748
}
// 跳转视频会诊页面
export function routerVideo(content) {
  getUserProfile(content.inviteeList).then(res => {
    console.log(res, 'res_________')
    store.commit('setCallData', {
      ...content,
      avatarList: res,
      actionUser: 'invited',
      action: content.actionType
    })
    content.room_id = content.roomId
    let url = `/pages/consultationVideo/call/index?args=${JSON.stringify({ content })}&from=${content.inviter}`
    wxNavigateTo(url)
  })
}
export function overConsultationChat(content) {
  let id = content.groupID.split('_')[1]
  videoRefuse(id, 'health_groupVideo')
}
export function clearCall() {
  store.commit('setIsCall', false)
  store.commit('setCalling', false)
  store.commit('setCallData', { action: '', data: {} })
}
export function videoRefuse(currentConversationID, key) {
  console.log(store.getters.isCalling, 'store.getters.isCalling')
  hangOffDoctor(currentConversationID, key)
  setTimeout(() => {
    clearCall()
  }, 1000)
}
export function noCallHangOff(currentConversationID, key) {
  let page = store.getters.currentPage
  if (page.indexOf('consultation/consultationChat') != -1) {
    let consultationId = getParam(page, 'id')
    if (consultationId != currentConversationID) {
      store.commit('setCurrentConversationID', `GROUPhealth_${consultationId}`)
    } else {
      let user = `GROUPhealth_${currentConversationID}`
      store.dispatch("checkoutConversation", user)
    }
    if (!key) {
      setTimeout(() => {
        wxNavigateBack()
      }, 500)
    } else {
      if (!getParam(page, 'query') && page.indexOf('teamVideo/groupCall' != -1) && !getParam(page, 'evaluateType')) {
        setTimeout(() => {
          wxNavigateBack()
        }, 500)
      }
    }
  } else {
    // 视频页面
    if (store.getters.consultationId != currentConversationID) {
      let user = `GROUPhealth_${store.getters.consultationId}`
      store.dispatch("checkoutConversation", user)
    }
    setTimeout(() => {
      console.log('返回页面')
      wxNavigateBack()
    }, 500)
  }
}
// 接听之后医生挂断
export function hangOffDoctor(id, key) {
  let user = `GROUPhealth_${id}`
  store.dispatch("checkoutConversation", user).then(res => {
    let url = `/pages/consultation/consultationChat/index?id=${id}&query=back`
    wxReLaunch(url)
  })
}
// 视频跳转
export function callAndConsultationRoute(videoCustom, item) {
  console.log('callAndConsultationRoute')
  let id = item.to.split('_')[1]
  switch (Number(videoCustom.action)) {
    // 对方呼叫我
    case 0:
      if (!store.getters.isCalling) {
        let obj = {
          action: 0,
          actionUser: 'invited',
          actionType: 1,
          avatarList: [],
          groupID: item.to,
          inviteeList: [item.from, store.getters.hisUserInfo.userNo],
          inviter: item.from,
          inviterName: item.nick,
          isFromGroup: true,
          key: "health_video",
          roomId: id,
          room_id: id
        }
        console.log(obj, 'inviteeList')
        store.commit('setCallData', obj)
        let url = `/pages/consultationVideo/call/index?args=${item.payload.data}&from=${item.from}`
        wxNavigateTo(url)
      } else {
        $bus.$emit('isCalling', item)
      }
      break
    // 对方取消
    case 1:
      videoRefuse(id)
      break
    // 对方拒绝
    case 2:
      $bus.$emit('onRefuse')
      break
    // 对方不接1min
    case 3:
      videoRefuse(id)
      break
    // 对方接听
    case 4:
      $bus.$emit('onCall', videoCustom)
      break
    // 对方挂断
    case 5:
      videoRefuse(id)
      break
    // 对方正在通话中
    case 6:
      $bus.$emit('onBusy')
      break
    default:
      break
  }
}

// 登录成功之后判断是否有待接听的视频问诊
export function isLoginVideoChat(arr) {
  setTotalUnreadCount(arr)
  if (arr[0] && arr[0].lastMessage.type === 'TIMCustomElem') {
    let fromAccount = arr[0].lastMessage.fromAccount
    let content = arr[0].lastMessage.payload.data
    let data = JSON.parse(content)
    // 视频问诊
    if (data.key === 'health_video' && data.content.action === 0) {
      if (!store.getters.isCalling) {
        data.key = 'health_video'
        data.inviteeList = [fromAccount, store.getters.hisUserInfo.userNo]
        data.inviter = fromAccount
        store.commit('setCallData', data)
        let url = `/pages/consultationVideo/call/index?args=${content}&from=${fromAccount}`
        wxNavigateTo(url)
      }
    }
    // 视频会诊
    if (data.key === 'health_groupVideo' && Number(data.actionType) <= 3) {
      console.log(store.getters.isCalling)
      console.log(store.getters.isCall, 'isCall')
      if (!store.getters.isCalling && !store.getters.isCall) {
        let index = data.inviteeList.indexOf(store.getters.hisUserInfo.userNo)
        if (index !== -1) {
          routerVideo(data)
        }
      }
    }
  }
}

// 支付成功之后跳转诊室
export function payOkRouterChat(wxPayment, consultationId) {
  wxPayApi(wxPayment).then((respon) => {
    store.commit('resetCurrentConversation')
    if (respon.errMsg === 'requestPayment:ok') {
      // 返回问诊id
      this.getGroupId(consultationId)
    }
  })
}
// 获取群信息
export function getGroupId(consultationId) {
  if (store.getters.consultationInfo && store.getters.consultationInfo.consultationTypeId == 7) {
    store.commit('setQuickConsultationStep', 6)
    wxReLaunch('/pages/quickConsultation/consultationFlow/index?id=' + consultationId)
  } else {
    this.sendEvent(`GROUPhealth_${consultationId}`)
  }
}
// 跳转诊室页面
export function sendEvent(groupID, consultationId) {
  store.dispatch('checkoutConversation', groupID).then(() => {
    store.commit('setDeptTypeId', '')
    store.commit('setConsultationOrder', null)
    wxReLaunch(`/pages/consultation/consultationChat/index?id=${consultationId}`)
  })
}
export function routerView() {
  setTimeout(() => {
    if (this.consultationInfo.consultationTypeId == 7) {
      store.commit('setQuickConsultationStep', 1)
    }
    wxReLaunch('/pages/consultation/consultationList/main')
  }, 2000)
}